package net.url;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.CacheResponse;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SimpleCacheResponse extends CacheResponse
{
	private Map<String,List<String>> headers;
	private SimpleCacheRequest request;
	private Date expires;
	public SimpleCacheResponse(SimpleCacheRequest request,URLConnection cu)
	{
		this.request = request;
		Map<String, List<String>> headers = new HashMap<String, List<String>>();
		String value = "";
		for (int i = 0; ; i++)
		{
			String name = cu.getHeaderFieldKey(i);
			if(value==null) break;
			List<String> values = headers.get(name);
			if(values==null)
			{
				values=new ArrayList<String>(1);
				headers.put(name, values);
			}
		}
		long expiration = cu.getExpiration();
		if(expiration!=0)
		{
			this.expires = new Date(expiration);
		}
		this.headers = Collections.unmodifiableMap(headers);
	}
	@Override
	public Map<String, List<String>> getHeaders() throws IOException
	{
		
		return headers;
	}

	@Override
	public InputStream getBody() throws IOException
	{
		return new ByteArrayInputStream(request.getData());
	}
	public boolean isExpired()
	{
		Date now = new Date();
		return expires.before(now);
	}
	
}
